<template>
	<view class="e-tabbar">
		<view :id="elId" class="e-tabbar__content" ref="tabbarRef" @touchmove.stop.prevent="noop"
			:class="[props.border && 'e-border-top', props.fixed && 'e-tabbar--fixed']" :style="[tabbarStyle]">
			<view class="e-tabbar__content__item-wrapper">
				<slot />
			</view>
			<e-safe-bottom v-if="props.safeAreaInsetBottom"></e-safe-bottom>
		</view>
		<view class="e-tabbar__placeholder" v-if="props.placeholder" :style="{
				height: placeholderHeight + 'px',
			}"></view>
	</view>
</template>
<script lang="ts">
	import { defineComponent } from 'vue'
	import mpMixin from '../../libs/mixin/mpMixin'
	/**
		 * Tabbar 底部导航栏
		 * @description 此组件提供了自定义tabbar的能力。
		 * @tutorial https://www.uviewui.com/components/tabbar.html
		 * @property {String | Number}	value				当前匹配项的name
		 * @property {Boolean}			safeAreaInsetBottom	是否为iPhoneX留出底部安全距离（默认 true ）
		 * @property {Boolean}			border				是否显示上方边框（默认 true ）
		 * @property {String | Number}	zIndex				元素层级z-index（默认 1 ）
		 * @property {String}			activeColor			选中标签的颜色（默认 '#1989fa' ）
		 * @property {String}			inactiveColor		未选中标签的颜色（默认 '#7d7e80' ）
		 * @property {Boolean}			fixed				是否固定在底部（默认 true ）
		 * @property {Boolean}			placeholder			fixed定位固定在底部时，是否生成一个等高元素防止塌陷（默认 true ）
		 * @property {Object}			customStyle			定义需要用到的外部样式
		 * 
		 * @example <e-tabbar :value="value2" :placeholder="false" @change="name => value2 = name" :fixed="false" :safeAreaInsetBottom="false"><e-tabbar-item text="首页" icon="home" dot ></e-tabbar-item></e-tabbar>
		 */
	export default defineComponent({
		name: "e-tabbar",
		mixins: [mpMixin]
	});
</script>

<script lang="ts" setup>
	import { ref, reactive, computed, watch, toRefs, getCurrentInstance, provide } from 'vue'
	import { tabbarProps, tabbarEmits } from './props';
	import {
		addStyle,
		noop
	} from '../../libs/utils/_utils'
	import {
		deepMerge,
		sleep,
		nanoid,
		getRect,
		getNvueRect,
	} from '../../libs/utils'
	import {
		useDefaultProps
	} from '../../libs/hooks'
	import type {
		 TabbarProps
	} from "../../libs/config/propsType";
	import componentsProps from "../../libs/config/componentsProps";
	import { type TabbarContext, type TabbarItemContext, tabbarContextKey } from '../../libs/tokens'

	const {
		tabbar: tabbarDefaultProps
	} = toRefs(componentsProps);

	const ctx = getCurrentInstance()

	const _props = defineProps(tabbarProps)
	const emit = defineEmits(tabbarEmits)

	const props = useDefaultProps<TabbarProps>(_props, tabbarDefaultProps);


	const placeholderHeight = ref(0)


	const tabbarStyle = computed(() => deepMerge({
		zIndex: props.value.zIndex
	}, addStyle(props.value.customStyle as Record<string, any>) as Record<string, any>))


	const children : TabbarItemContext[] = []

	const addField : TabbarContext['addField'] = (field) => {
		children.push(field)
	}

	const removeField : TabbarContext['removeField'] = (field) => {
		let index = children.indexOf(field)
		if (index > -1) {
			children.splice(index, 1)
		}
	}

	const getChildIndex : TabbarContext['getChildIndex'] = (id) => children.findIndex(item => item.id === id)

	const change : TabbarContext['change'] = (name) => {
		emit('change', name)
	}

	const updateChildren = () => {
		// 如果存在子元素，则执行子元素的updateFromParent进行更新数据
		children.map(child => child.updateFromParent())
	}
	const elId = ref(nanoid(21, true))
	const tabbarRef = ref()
	// 设置用于防止塌陷元素的高度
	const setPlaceholderHeight = async () => {
		if (!props.value.fixed || !props.value.placeholder) return
		// 延时一定时间
		await sleep(20)
		// #ifndef APP-NVUE
		getRect(ctx, `#${elId.value}`).then(size => {
			placeholderHeight.value = size.height || 50
		})
		// #endif

		// #ifdef APP-NVUE
		getNvueRect(tabbarRef.value).then(size => {
			placeholderHeight.value = size.height || 50
		})
		// #endif
	}

	watch(() => [props.value.value, props.value.activeColor, props.value.inactiveColor], () => {
		updateChildren()
	})
	watch(() => [props.value.fixed, props.value.placeholder], () => {
		setPlaceholderHeight()
	}, {
		immediate: true
	})

	provide(tabbarContextKey, reactive({
		props,
		addField,
		removeField,
		getChildIndex,
		change
	}))
</script>

<style lang="scss" scoped>
	@import "../../libs/theme/tabbar.scss";
</style>